/*
 * @描述: 联动列表组件
 * @Author: /songzi
 * @Date: 2020-02-17 09:51:03
 * @Last Modified by:   songzi
 * @Last Modified time: 2020-02-17 09:51:03
 */

import React, { PureComponent } from 'react';
import { generate as generateId } from 'shortid';
import { Select, Button, Icon } from 'antd';
import styles from './DynamicList.less';

const { Option } = Select;
const revValue = value => {
  const valArr = value.split('.');
  return {
    value: valArr.pop(),
    groupName: valArr.shift(),
    eventName: valArr[0] || ''
  };
};

const checkSelected = (value, optionItem) => {
  const { name } = optionItem;
  const hasVal = value.filter(item => {
    const $val = item.split('.').pop();
    return $val === name;
  });
  return !!hasVal.length;
};

class DynamicList extends PureComponent {
  constructor(props) {
    super(props);
    const { value, defaultValue } = props;
    this.state = {
      value: value || defaultValue
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      value: nextProps.defaultValue && nextProps.defaultValue.length > 0 ? nextProps.defaultValue : ['all']
    });
  }

  selectChange = (newValue, index, itemInfo) => {
    let setVal = 'all';
    if (newValue !== 'all') {
      const { options } = this.props;
      const selectItem = options.filter(item => item.name === newValue)[0];
      const eventName = selectItem.event_name;
      const { groupName } = selectItem;
      setVal = `${groupName}.${eventName ? `${eventName}.` : ''}${newValue}`;
    }
    this.setState(
      oldState => {
        const { value: valueState } = oldState;
        valueState[index] = setVal;
        return { value: [...valueState] };
      },
      () => {
        this.actionChange(setVal);
      }
    );
  };

  handleDelete = (index, value) => {
    this.setState(
      oldState => {
        const { value: valueState } = oldState;
        valueState.splice(index, 1);
        return { value: [...valueState] };
      },
      () => {
        if (value !== 'all') this.actionChange();
      }
    );
  };

  actionChange = () => {
    const { onChange } = this.props;
    if (onChange) {
      const valueState = this.state.value;
      onChange(valueState.filter(item => item !== 'all'));
    }
  };

  handleAdd = () => {
    this.setState(oldState => {
      const { value: valueState } = oldState;
      valueState.push('all');
      return { value: [...valueState] };
    });
  };

  getGroupsOptions = (options, value, groupName, groups) => {
    if (groups && groups.length) {
      return groups.map(group => {
        const groupOptions = options.filter(item => item[groupName] === group.value);
        return (
          <Select.OptGroup key={group.value} label={group.name}>
            {this.getOptions(groupOptions, value)}
          </Select.OptGroup>
        );
      });
    }
    return this.getOptions(options, value);
  };

  getOptions = (options, value) =>
    options.map((optionItem, optionIndex) => {
      const keys = `option_${optionIndex}`;
      return (
        <Option key={optionItem.name || keys} value={optionItem.name} disabled={checkSelected(value, optionItem)}>
          {optionItem.cname || optionItem.name}
        </Option>
      );
    });

  render() {
    const { selectChange, handleAdd, handleDelete } = this;
    const { options, titleText, expand, groupName = 'groupName', groups } = this.props;

    const { value = [] } = this.state;
    return (
      <div className={styles.dynamiclist}>
        {/* <TransitionGroup> */}
        {value.map((item, index) => (
          // <CSSTransition timeout={150} classNames="fade" >
          <div key={generateId()} className={`${styles.item} clearfix`}>
            <div className={styles.title}>{titleText && titleText} </div>
            <div className={styles.content}>
              <Select
                showSearch
                filterOption={(input, option) => {
                  let { children = '' } = option.props;
                  const { value: optValue } = option.props;
                  if (children instanceof Array) {
                    children = children.find(
                      oitem =>
                        oitem.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                        oitem.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    );
                    return children && children.length > 0;
                  }
                  if (children.toLowerCase().indexOf(input.toLowerCase()) >= 0) return true;
                  if (optValue !== 'all' && optValue.toLowerCase().indexOf(input.toLowerCase()) >= 0) return true;
                  return false;
                }}
                onChange={$value => {
                  selectChange($value, index);
                }}
                defaultValue={revValue(item).value || 'all'}
                style={{ width: 180 }}
              >
                <Option value="all">总体</Option>
                {this.getGroupsOptions(options, value, groupName, groups)}
              </Select>
            </div>
            <div className={styles.expand}>{expand && expand}</div>
            <div className={styles.optBtnGroup}>
              {value.length > 1 && (
                <Button
                  onClick={() => {
                    handleDelete(index, item);
                  }}
                  shape="circle"
                  size="small"
                >
                  <Icon type="close"></Icon>
                </Button>
              )}
              {index === value.length - 1 && (
                <Button className={styles.alwasShow} onClick={handleAdd} type="primary" shape="circle" size="small">
                  <Icon type="plus"></Icon>
                </Button>
              )}
            </div>
          </div>
          // </CSSTransition>
        ))}
        {/* </TransitionGroup> */}
      </div>
    );
  }
}
export default DynamicList;
